package com.vehiclemanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vehiclemanagement.entity.OperationLog;
import com.vehiclemanagement.mapper.OperationLogMapper;
import com.vehiclemanagement.service.OperationLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

/**
 * 操作日志服务实现类
 */
@Service
@Slf4j
public class OperationLogServiceImpl extends ServiceImpl<OperationLogMapper, OperationLog> implements OperationLogService {

    @Autowired
    private OperationLogMapper operationLogMapper;

    @Override
    public boolean saveLog(OperationLog operationLog) {
        if (operationLog.getCreateTime() == null) {
            operationLog.setCreateTime(LocalDateTime.now());
        }
        return save(operationLog);
    }

    @Override
    public IPage<OperationLog> pageLogs(Integer current, Integer size, String username, String module, Integer operationType, 
                                        Integer status, LocalDateTime startTime, LocalDateTime endTime) {
        Page<OperationLog> page = new Page<>(current, size);
        StringBuilder whereSql = new StringBuilder(" WHERE 1=1 ");

        if (StringUtils.hasText(username)) {
            whereSql.append(" AND username LIKE '%").append(username).append("%'");
        }

        if (StringUtils.hasText(module)) {
            whereSql.append(" AND module = '").append(module).append("'");
        }

        if (operationType != null) {
            whereSql.append(" AND operation_type = ").append(operationType);
        }

        if (status != null) {
            whereSql.append(" AND status = ").append(status);
        }

        if (startTime != null) {
            whereSql.append(" AND create_time >= '").append(startTime).append("'");
        }

        if (endTime != null) {
            whereSql.append(" AND create_time <= '").append(endTime).append("'");
        }

        return operationLogMapper.selectPageLogs(page, whereSql.toString());
    }

    @Override
    public int clearLogs(Integer days) {
        if (days == null || days <= 0) {
            log.error("清除日志天数不能小于等于0");
            return 0;
        }

        LocalDateTime clearBefore = LocalDateTime.now().minus(days, ChronoUnit.DAYS);
        LambdaQueryWrapper<OperationLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.lt(OperationLog::getCreateTime, clearBefore);

        long countLong = count(queryWrapper);
        
        int count = (int) Math.min(countLong, Integer.MAX_VALUE);
        
        if (count > 0) {
            boolean success = remove(queryWrapper);
            if (success) {
                log.info("成功清除{}天前的{}条日志记录", days, count);
                return count;
            }
        }
        return 0;
    }

    @Override
    public int countUserOperations(Long userId, LocalDateTime startTime, LocalDateTime endTime) {
        if (userId == null) {
            return 0;
        }
        if (startTime == null) {
            startTime = LocalDateTime.now().minusDays(30);
        }
        if (endTime == null) {
            endTime = LocalDateTime.now();
        }
        return operationLogMapper.countUserOperations(userId, startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> statisticsByOperationType(LocalDateTime startTime, LocalDateTime endTime) {
        if (startTime == null) {
            startTime = LocalDateTime.now().minusDays(30);
        }
        if (endTime == null) {
            endTime = LocalDateTime.now();
        }
        return operationLogMapper.statisticsByOperationType(startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> statisticsByModule(LocalDateTime startTime, LocalDateTime endTime) {
        if (startTime == null) {
            startTime = LocalDateTime.now().minusDays(30);
        }
        if (endTime == null) {
            endTime = LocalDateTime.now();
        }
        return operationLogMapper.statisticsByModule(startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> statisticsByDate(LocalDateTime startTime, LocalDateTime endTime) {
        if (startTime == null) {
            startTime = LocalDateTime.now().minusDays(30);
        }
        if (endTime == null) {
            endTime = LocalDateTime.now();
        }
        return operationLogMapper.statisticsByDate(startTime, endTime);
    }
} 